import { Constant } from '../../constants/Constant';
import { Messages } from '../../constants/Messages';

const { ccclass, property, menu } = cc._decorator;

const RunningState = Constant.RunningState;

@ccclass
@menu("Tweens/ActiveThing")
export default class ActiveThing extends cc.Component {

    @property({ type: cc.Enum(RunningState) })
    mode: Constant.RunningState = RunningState.Idle;
    @property
    isLoop: boolean = false;
    @property
    isAuto: boolean = false;
    @property({ min: 1 })
    cycleTimes: number = 1;
    @property({ type: [cc.Vec2], tooltip: "y=0 is using as inactive while others as active" })
    activeItems: cc.Vec2[] = [];
    @property
    callTag: number = 0;
    @property(cc.Node)
    targetNode: cc.Node = null;

    _tikPast: number = 0;
    _itemCursor: number = 0;
    _cycleTimes: number = 0;

    onLoad() {
        this._initEvents();
    }

    onEnable() {
        this.isAuto ? this.mode = RunningState.Running : null;
        this.cycleTimes < 1 ? this.cycleTimes = 1 : null;
        this._cycleTimes = this.cycleTimes;
        this._itemCursor = 0;
        this._tikPast = 0;
    }

    start() { }

    protected update(dt: number): void {
        this._calculate(dt);
    }

    _initEvents() {
        this.node.on(Messages.Nodes.StateChangePause, () => {
            this.mode = RunningState.Paused;
        }, this);
        this.node.on(Messages.Nodes.StateChangeRun, (callTag?: number, reset: boolean = true) => {
            reset && this.onEnable();
            if (callTag == null || callTag == this.callTag) {
                this.mode = RunningState.Running;
            }
        }, this);
        this.node.on(Messages.Nodes.StateChangeStop, () => {
            this.mode = RunningState.Stop;
        }, this);
        this.node.on(Messages.Nodes.ThingSetChangeActive, (items: cc.Vec2[]) => {
            items ? this.activeItems = items : null;
            this._itemCursor = 0;
            this._tikPast = 0;
        }, this);
    }

    _calculate(dt: number = 0) {
        switch (this.mode) {
            case RunningState.Running:
                if (this.activeItems.length <= 0) return;
                this._tikPast = this._tikPast + dt;
                break
            default: return;
        }

        if (this._tikPast >= this.activeItems[this._itemCursor].x) {
            this.targetNode.active = this.activeItems[this._itemCursor].y != 0;
            this._tikPast = this._tikPast - this.activeItems[this._itemCursor].x;
            this._itemCursor++;
        }

        if (this._itemCursor >= this.activeItems.length) {
            this._itemCursor = 0;
            if (this.isLoop) {
                return;
            }
            this._cycleTimes--;
            if (this._cycleTimes < 1) {
                this.mode = RunningState.Idle;
                return;
            }
        }
    }
}
